<template>
  <div class="NavigationBar">
    <el-tabs
      v-model="editableTabsAtive"
      type="card"
      :closable="editableTabs.length > 1"
      @tab-remove="removeTab"
      @tab-click="clickTab"
    >
      <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name"></el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { reactive, toRefs, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
export default {
  setup() {
    const $route = useRoute()
    const $router = useRouter()
    const data = reactive({
      editableTabsAtive: 0,
      editableTabs: [],
    })
    watch(
      $route,
      (to, from) => {
        const isExist = data.editableTabs.some(item => item.path === to.path)
        // 如果跳转的路由已存在当前栈
        if (isExist) {
          data.editableTabsAtive = data.editableTabs.indexOf(data.editableTabs.filter((item) => item.path === to.path)[0]);
        } else {
          data.editableTabs.push({
            path: to.path,
            title: to.meta.title,
            name: data.editableTabs.length,
          });
          data.editableTabsAtive = data.editableTabs.length - 1;
        }
      },
      { immediate: true }
    )
    const methods = {
      clickTab(target) {
        const path = data.editableTabs[target.index].path
        if ($route.path !== path) $router.push(path)
      },
      removeTab(index) {
        if (data.editableTabsAtive === index) {
          let target = data.editableTabs[index + 1] || data.editableTabs[index - 1];
          $router.push(target.path)
        }
        data.editableTabs.splice(index, 1)
        data.editableTabs.forEach((v ,i) => v.name = i)
      },
    }
    return {
      ...toRefs(data),
      ...methods
    }
  }
}
</script>

<style lang="scss" scoped>
.NavigationBar {
  width: 100%;
  border-top: 1px solid #e4e7ed;
}
</style>

<style lang="scss">
.NavigationBar {
  .el-tabs {
    .el-tabs__header {
      height: 29px;
      margin: 0;
    }
    .el-tabs__content {
      display: none;
    }
    .el-tabs__item {
      height: 30px;
      line-height: 30px;
      // margin: 0;
      // border-bottom: none !important;
    }
    .el-tabs__nav-prev {
      height: 30px;
      line-height: 30px;
    }
    .el-tabs__nav-next {
      height: 30px;
      line-height: 30px;
    }
    .el-tabs__nav {
      border-top: none !important;
    }
    .el-tabs__item.is-top.is-active {
      // background-color: #41b88310;
    }
  }
}
</style>